package org.example.mall.admin.configuration.auth;

import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.example.mall.admin.configuration.auth.grant.CustomAuthenticationProvider;
import org.example.mall.admin.util.SecurityUtil;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;

/**
 * @author hzq
 * @date 2021/12/6 10:41
 */
@Configuration
@EnableWebSecurity
@AllArgsConstructor
public class WebSecurityAuthorizationConfiguration extends WebSecurityConfigurerAdapter {

    private final CustomUserDetailsService userDetailsService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authenticationProvider(CustomAuthenticationProvider.build(userDetailsService));
    }

    @Bean
    @Override
    @SneakyThrows
    public AuthenticationManager authenticationManagerBean() {
        return super.authenticationManagerBean();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return SecurityUtil.PASSWORD_ENCODER;
    }

    @Bean
    public TokenStore tokenStore(RedisConnectionFactory connectionFactory) {
        RedisTokenStore tokenStore = new RedisTokenStore(connectionFactory);
        tokenStore.setPrefix("oauth:");
        return tokenStore;
    }
}
